import React, { Component } from 'react'
import CollectionList from './CollectionList'
import FlowerList from './FlowerList'

export default class Display extends Component {
    state = {
        list: [], 
        collection: JSON.parse(localStorage.getItem('collection')) || []
    }
    componentDidMount() {
        fetch('https://www.fastmock.site/mock/3c02a69b3952632e311022710cb48a6c/plant/getPlants')
            .then(res=>res.json())
            .then(res=>{
                this.setState({list: res.result.plantList})
            })
    }
    
    addItem = (flower) => {
        if(this.state.collection.indexOf(flower) === -1 ) {
            this.setState({
                collection:[
                    flower,
                     ...this.state.collection
                    ]
            },() => {
                localStorage.setItem(
                    'collection',
                    JSON.stringify(this.state.collection)
                ) 
            })
        }
    }
    delItem = (i) => {
        let newCollection = this.state.collection.filter((item)=>i!=item)
        this.setState({collection:newCollection})
        localStorage.setItem(
            'collection',
            JSON.stringify(newCollection)
        )
    }
    render() {
        const {list, collection} = this.state;
        return (
            <div className="page">
                <CollectionList collection={collection} delItem={this.delItem} />
                <FlowerList list={list} collection={collection} addItem={this.addItem} />
            </div>
        )
    }
}
